//
//  GradientProgressView.swift
//  SCA
//
//  Created by tjun on 2025/9/14.
//

import UIKit

/// 渐变进度条
class GradientProgressView: UIView {
    
    var progress: CGFloat = 0 {
        didSet {
            progress = min(max(progress, 0), 1) // 限制在 0~1
            setNeedsLayout()
        }
    }
    
    var colors: [UIColor] = [UIColorMake(0x05D4FC), UIColorMake(0xBE0DEF), UIColorMake(0xF202D3)] {
        didSet {
            gradientLayer.colors = colors.map { $0.cgColor }
        }
    }
    
    private let gradientLayer = CAGradientLayer()
    private let progressLayer = CALayer()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupLayers()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setupLayers()
    }
    
    private func setupLayers() {
        progressLayer.backgroundColor = UIColor.black.cgColor
        layer.addSublayer(progressLayer)
        
        gradientLayer.startPoint = CGPoint(x: 0, y: 0.5)
        gradientLayer.endPoint = CGPoint(x: 1, y: 0.5)
        gradientLayer.colors = colors.map { $0.cgColor }
        gradientLayer.mask = progressLayer
        layer.addSublayer(gradientLayer)
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        gradientLayer.frame = bounds
        progressLayer.frame = CGRect(x: 0, y: 0, width: bounds.width * progress, height: bounds.height)
        progressLayer.cornerRadius = bounds.height / 2
    }
    
    func setProgress(_ value: CGFloat, animated: Bool, duration: TimeInterval = 0.25) {
        if animated {
            let fromWidth = progressLayer.frame.width
            let toWidth = bounds.width * min(max(value, 0), 1)
            
            let animation = CABasicAnimation(keyPath: "bounds.size.width")
            animation.fromValue = fromWidth
            animation.toValue = toWidth
            animation.duration = duration
            animation.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
            
            progressLayer.bounds.size.width = toWidth
            progressLayer.add(animation, forKey: "width")
            
            progress = value
        } else {
            progress = value
        }
    }
}
